package cn.tonyqiu.gaecash.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import cn.tonyqiu.gaecash.model.Bill;
import cn.tonyqiu.gaecash.model.Label;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;

public class BillController extends MultiActionController {

	private static final Logger log = Logger.getLogger(BillController.class.getName());
	
	public void add(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		// TODO add bill
		Bill bill = new Bill();
		List<Label> labels = new ArrayList<Label>();
		User user = UserServiceFactory.getUserService().getCurrentUser();
		try {
			bill.setDate(Util.parseDate(req.getParameter("date")));
			bill.setUser(user);
			bill.setRemark(req.getParameter("remark"));
			bill.setAmount(Double.parseDouble(req.getParameter("amount")));
			String labelsParam = req.getParameter("labels");
			for (String labelName : labelsParam.split(",")) {
				labels.add(new Label(labelName, user));
			}
			bill.setLabels(labels);
			bill = bill.add();
			resp.getWriter().write(bill.getKeyString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public ModelAndView del(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		String delIdString = req.getParameter("delIdString");
		for (String keyString : delIdString.split(",")) {
			Bill.del(keyString);
		}
		return null;
	}

	public void edit(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		try {
		User user = UserServiceFactory.getUserService().getCurrentUser();
		Bill bill = new Bill();
		bill.setKeyString(req.getParameter("keystring"));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		bill.setDate(sdf.parse(req.getParameter("date")));
		String labelString = req.getParameter("labels");
		List<Label> labels = new ArrayList<Label>();
		for(String label: labelString.split(",")) {
			labels.add(new Label(label,user));
		}
		bill.setLabels(labels);
		bill.setRemark(req.getParameter("remark"));
		bill.setAmount(Double.parseDouble(req.getParameter("amount")));
		bill.setUser(user);
		bill.edit();
		}catch(Exception e) {
			resp.getWriter().write("-1:"+e.getMessage());
		}
	}

	public ModelAndView getByPage(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		// TODO get bills by page
		int start = 0;
		int count = 20;
		try {
			start = Integer.parseInt(req.getParameter("start"));
			count = Integer.parseInt(req.getParameter("count"));
			
		} catch (NumberFormatException nfe) {
			// TODO to deal with the exception
		}
		if(start <=0) start = 0;
		if(count <=0) start = 20;
		User user = UserServiceFactory.getUserService().getCurrentUser();
		
		//getFilter parameters
		String filterFromStr = req.getParameter("filterFrom");
		Date filterFrom = null;
		if(filterFromStr != null) {
			try {
				filterFrom = Util.parseDate(filterFromStr);
			}catch(ParseException e) {
				filterFrom = null;
				log.warning("ivalid filter date from input");
			}
		}
		
		String filterToStr = req.getParameter("filterTo");
		Date filterTo = null;
		if(filterToStr != null) {
			try {
				filterTo = Util.parseDate(filterToStr);
			}catch(ParseException e) {
				filterTo = null;
				log.warning("ivalid filter date to input");
			}
		}
				
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		if(filterFrom != null || filterTo != null){
			Map<String,Object> billMap = Bill.filterByDate(user, start, count, filterFrom, filterTo);
			map.put("bills", billMap.get("bills"));
			map.put("billInfo", billMap.get("billInfo"));
		}else {
			Map<String,Object> billMap = Bill.getByPage(user, start, count);
			map.put("bills",billMap.get("bills"));
			map.put("billInfo", billMap.get("billInfo"));
		}
		map.put("labels",Label.getAll(user));
		return new ModelAndView("WEB-INF/pages/bill.jsp", map);
	}

	public ModelAndView action(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		return getByPage(req, resp);
	}
}
